<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>聊天室</title>
    <script src="http://localhost:8080/socket.io/socket.io.js"></script>
    <style>
        .mine{
            background: green;
        }
    </style>
</head>
<body>
    <p>当前在线人数:<span id="num"></span>人</p>
    <hr>
    <form  name='frm'>
        账号：<input type="text" name='username' ><br />
        密码：<input type="password" name="userpwd"><br />
        <button id="btn1" type="button">登录</button>
        <button id="btn2" type="button">注册</button>
    </form>
    <hr >
    <textarea name="" id="text" cols="100" rows="4"></textarea><br />
    <button id='send' type="button">发送</button><br />
    <ul id="ul"></ul>
</body>
<script  src="/jquery-3.2.1.min.js"></script>

<script>
    var current_name = '';
    var socket = io('ws://localhost:8080'); 

    socket.emit( 'count');
    socket.on( 'count_ret',data=>{
        $('#num').text( data );
    } );

    //注册
    socket.on( 'reg_ret',(code,msg)=>{
        alert( msg );
    });

    //登录
    socket.on( 'login_ret',(code,msg)=>{
        alert(msg);
        if( !code )
        {
            current_name = $('input[name=username]').val();
        }
    } );

    //广播
    /* socket.on( 'broadcast',(msg)=>{
        alert( msg );
    } ); */


    //发送回执消息
    socket.on( 'msg_ret',(code,msg)=>{
        if( code )
        {
            alert( msg );
        }else{
            var li = `<li class='mine'><h4>【${current_name}】说：</h4><p>${$('#text').val()}</p></li>`;
            $('#ul').append( li );
        }
    } );

    socket.on( 'msg',(current_user_name,msg)=>{
        var li = `<li class=''><h4>【${current_user_name}】说：</h4><p>${msg}</p></li>`;
        $('#ul').append( li );
    } );

    $("#btn1").click(function(){
        socket.emit('login',$('input[name=username]').val(),$('input[name=userpwd]').val());
    });

    $("#btn2").click(function(){
        socket.emit( 'reg',$('input[name=username]').val(),$('input[name=userpwd]').val() );
    });

    //发送消息
    $('#send').click(function(){
        var msg = $('#text').val();
        socket.emit( 'msg',msg );
        
    });
</script>
</html>